import CCLog from "../CCLog";
import { AUDIOS_PATH } from "../Common/AudioConfig";
import { BLOCK_ELIMINATE_LIMIT, CATCHER_ZINDEX, CUSTOM_EVENT_NAME } from "../Common/Constant";
import { GameData, GetAccountInfo, GetAccountInfo_WithoutAniml, GetReceiveAward } from "../Common/GameData";
import { JsbTileTrileTileCallMgr } from "../Common/JsbMgr";
import SingleCatcherController from "../Game/SingleCatcherController";
import GameTileStaticData from "../GameStaticData";
import getEventEmiter from "../Libraries/EventEmitter";
import AudioTool from "../System/AudioSystem";
import SceneManagerSystem from "../System/SceneManagerSystem";
import { BizTypeEnum } from "../net/api";
import GamePlayController from "./GamePlayController";
import ProgressController from "./ProgressController";
import SingleBlockController from "./SingleBlockController";

const { ccclass, property } = cc._decorator;

@ccclass
export default class CatcherController extends cc.Component {
    public static I: CatcherController;

    @property([SingleCatcherController])
    catchers: SingleCatcherController[] = [];

    private _blockCatched: SingleBlockController[] = [];

    public onLoad() {
        CatcherController.I = this;
        this.node.parent.zIndex = CATCHER_ZINDEX;
    }

    /**
     * 接收区接收方块 返回是否有空余位置接收
     * @param block 被接收的方块
     */
    public catchOneBlock(block: SingleBlockController): boolean {
        let blankCatcher: SingleCatcherController = this.catchers.find(v => !v.getCurrentBlock());
        if (!blankCatcher) return false;
        let same: SingleBlockController[] = this._blockCatched.filter((v: SingleBlockController) => {
            return !v.isEliminating && v.blockSkin.spriteFrame == block.blockSkin.spriteFrame;
        });
        if (same.length > 0) {
            let catchers = this.catchers;
            let index = catchers.indexOf(same[same.length - 1].stayCatcher);
            for (let i: number = catchers.length - 2; i > index; i--) {
                let cBlock = catchers[i].getCurrentBlock();
                if (!cBlock) continue;
                if (catchers[i + 1]) {
                    catchers[i + 1].catchBlock(cBlock);
                }
                if (catchers[i]) {
                    catchers[i].discardBlock();
                }
                
                
            }
            if (catchers[index + 1]) {
                catchers[index + 1].catchBlock(block);
            }
            
        } else {
            if (blankCatcher) {
                blankCatcher.catchBlock(block);
            }
            
        }
        this._blockCatched.push(block);
        return true;
    }

    /**
     * 接收块之后检测是否可以消除
     * @param blockType 最近收接收到的块的类型（类型通过spriteFrame判断）
     */
    public async checkEliminate(blockType: cc.SpriteFrame) {
        let same: SingleBlockController[] = this._blockCatched.filter((b: SingleBlockController) => {
            return !b.isMoving && b.blockSkin.spriteFrame == blockType;
        });
        
        if (same.length === BLOCK_ELIMINATE_LIMIT) {
            //AudioSystem.play(AUDIOS_PATH.block_eliminate);
            let promises: Promise<any>[] = [];
            //let isguider = (GameData.LevelData.passNum == 2 && GameData.LevelData.novice2 == 0)
            let isguider = (GameData.LevelData.passNum == 2 && GameData.AccountData.cointotal<=0)
          
            if (GamePlayController.I.isJinBiBlock(same[0]) && !isguider){
                SceneManagerSystem.showGetCoinOrLiBaoPanels("coin",0,()=>{  
                    
                });
            }else if (GamePlayController.I.isMoneyBlock(same[0])){
                SceneManagerSystem.showGetRedBagPanels("mergeMoney",()=>{
                    
                });
            }
            same.forEach((block: SingleBlockController, i: number) => {
               
                promises.push(block.eliminateSelf());
                this._blockCatched.splice(this._blockCatched.indexOf(block), 1);
            });
            await Promise.all(promises);
            JsbTileTrileTileCallMgr.handler("playMergeAudio","()V");
            AudioTool.play(AUDIOS_PATH.block_destory)
            // if (!GameStaticData.isShenHeModel) {
                
    
            //     //请求消除奖励
            //     let msg = await GetReceiveAward(BizTypeEnum.v2_clear,0)
            //     if (msg.resCode == 0){
            //         if (msg.data.rewardMoney>0) {
            //             CCLog.log("++++++++获取的消除奖励",msg.data.rewardMoney)
            //             same.forEach((block: SingleBlockController, i: number) => {
                    
            //                 block.stayCatcher.flyMoney(i)
            //             });
            //             GetAccountInfo_WithoutAniml(msg.data.rewardMoney);
            //         }
            //     }
            // }
           
           
            ProgressController.I.refresh();
            GamePlayController.I.checkResult();
            this.resetPosAfterEliminate();
        } else {
            GamePlayController.I.checkResult('checkEliminate');
        }
    }

    /**
     * 产生消除之后重新规划位置
     */
    public resetPosAfterEliminate(): void {
        let catchers = this.catchers;
        let blankNum: number = 0;
        for (let i: number = 0; i < catchers.length; i++) {
            let cBlock = catchers[i].getCurrentBlock();
            if (cBlock) {
                if (blankNum === 0) continue;
                catchers[i - blankNum].catchBlock(cBlock);
                catchers[i].discardBlock();
            } else {
                blankNum += 1;
            }
        }
    }

    /**
     * 撤回之后重新规划位置
     */
    public resetPosAfterRecall(): void {
        let blankCatcher: SingleCatcherController = this.catchers.find(v => !v.getCurrentBlock());
        for (let i: number = this.catchers.indexOf(blankCatcher) + 1; i < this.catchers.length; i++) {
            let b = this.catchers[i].getCurrentBlock();
            if (b) {
                this.catchers[i - 1].catchBlock(b);
                this.catchers[i].discardBlock();
            } else {
                return;
            }
        }
    }

    /**
     * 清除接接收区
     */
    public clean(): void {
        this.catchers.forEach((v) => {
            v.clean();
        });
    }

    /**
     * 返回接收区是否被占满
     */
    public isNotFull(): boolean {
        return this.catchers.some((v) => {
            let b = v.getCurrentBlock();
            return !b || b.isMoving || b.isEliminating;
        });
    }

    /**
     * 获取最近收集的一个块
     */
    public getLastBlock(): SingleBlockController {
        let block = this._blockCatched.pop();
        return block;
    }

    /**
     * 获取空闲接收区的数量
     */
    public getBlankCatcherNum(): number {
        return this.catchers.filter(v => !v.getCurrentBlock()).length;
    }
}
